<template>
	<view class="page_scroll_view">
		<tn-navbar fixed :bottom-shadow="false">结算周期配置</tn-navbar>
		<tn-sticky class="tn-white_bg">
			<view @click="showPopup=true" class="tn-flex items-center justify-between tn-p">
				<view class="tn-flex items-center">
					<tn-icon name="add-square" />
					<text class="tn-ml-xs">新增配置</text>
				</view>
				<tn-icon class="tn-text-right" type="info" name="right" />
			</view>
			<view class="tn-p-sm tn-pl tn-gray-light_bg">
				<text>共 {{total}} 条记录</text>
			</view>
		</tn-sticky>
		<loading v-if="isLoading" style="height: 70vh;"></loading>
		<view class="empty" style="height: 70vh;" v-else-if="configList.length == 0">
			<image
				src="https://sgymv1.oss-cn-beijing.aliyuncs.com/sgym/avatar/admin/2025/02/a0c4966b-11af-4c87-93aa-359f9c03d89f83ee61eba8e363790692eb5fd8a98de7.png"
				mode="widthFix"></image>
			<text>这里空空荡荡，啥也没有留下</text>
		</view>
		<scroll-view scroll-y="true" v-else>
			<view class="tn-p-sm">
				<view class="tn-radius card_item tn-p-sm tn-w-full" v-for="item in configList" :key="item.id"
					@click.stop="editPopup(item)">
					<view class="tn-flex items-center justify-between">
						<view class="tn-flex items-center">
							<tn-title :title="item.cycle_name" mode="hLine" assist-color="tn-blue" size="lg" />
							<tn-icon name="pushpin-fill" type="primary" class="tn-ml-xs" offset-top="-2rpx" />
						</view>
						<tn-switch @change="changeActiveSwitch($event,'is_default',item)" v-model="item.is_default"
							size="sm" :active-value="1" :inactive-value="0" active-text="默认" inactive-text="关闭" />
					</view>
					<view class="tn-flex tn-flex-column justify-around tn-mt-sm">
						<text class="tn-mt-xs">
							<text>周期比例：</text>
							<text class="tn-text-sm">{{item.cycle_rate}}%</text>
						</text>
						<text class="tn-mt-xs">
							<text>周期天数：</text>
							<text class="tn-text-sm">{{item.cycle_value}}天</text>
						</text>
						<text class="tn-mt-xs">
							<text>描述信息：</text>
							<text class="tn-text-sm">{{item.cycle_desc}}</text>
						</text>
					</view>
					<view
						class="tn-flex justify-between items-center tn-pt-sm tn-mt-sm tn-border-top tn-gray-light_border">
						<view class="tn-flex items-center">
							<tn-switch @change="changeActiveSwitch($event,'status',item)" v-model="item.status"
								size="sm" shape="square" :active-value="1" :inactive-value="0" active-text="启用"
								active-color="tn-green" inactive-text="禁用" />
						</view>

						<view class="tn-flex items-center">
							<text class="tn-mr-xs tn-text-xs tn-type-info_text">编辑配置</text>
							<tn-icon name="right" size="26" />
						</view>
					</view>
				</view>
				<view class="tn-pt-sm tn-pb-sm tn-flex-center">
					<uni-pagination :total="total" :current="query.page" :pageSize="query.limit" @change="changePage" />
				</view>
			</view>
		</scroll-view>
	</view>
	<tn-popup v-model="showPopup" open-direction="bottom" @close="closePopup">
		<view class="tn-p-lg tn-pt-sm">
			<view class="tn-flex-center-center tn-text-lg tn-mb-sm">
				{{config.id?'编辑':'新增'}}周期配置
			</view>
			<tn-form :model="config" ref="formRef" :rules="formRules" label-position="top">
				<tn-form-item label="账期" prop="cycle_value">
					<tn-input v-model="config.cycle_value" type="digit" placeholder="请输入账期（天数）" clearable
						@input="handleCycleValueInput" />
				</tn-form-item>
				<tn-form-item label="比例" prop="cycle_rate">
					<tn-input v-model="config.cycle_rate" type="digit" placeholder="请输入周期比例（1-100的正整数）" clearable
						@input="handleCycleRateInput" />
				</tn-form-item>
				<tn-form-item label="名称" prop="cycle_name">
					<tn-input v-model="config.cycle_name" placeholder="请输入名称（例如：T0）" clearable />
				</tn-form-item>
				<tn-form-item label="描述" prop="cycle_desc">
					<tn-input v-model="config.cycle_desc" type="textarea" placeholder="请输入描述信息" clearable />
				</tn-form-item>
			</tn-form>
			<view class="tn-flex-center">
				<tn-button size="lg" width="80vw" height="80" font-size="26"
					@click="submitForReview">{{config.id?'编辑':'新增'}}配置</tn-button>
			</view>
		</view>
	</tn-popup>
	<tn-modal ref="modalRef" />
</template>

<script setup>
	import {
		getSettleCycleConfigListApi,
		cycleUpdateApi,
		submitcycleTempApi
	} from "@/request/worktop/index.js"
	import {
		ref
	} from 'vue';
	import {
		onLoad
	} from "@dcloudio/uni-app"

	onLoad(() => {
		getSettleCycleConfigList()
	})

	const formRef = ref()
	const modalRef = ref()
	const showPopup = ref(false)
	const isLoading = ref(true)
	const config = ref({
		id: 0,
		cycle_type: 1,
		cycle_name: '',
		cycle_rate: '',
		cycle_value: '',
		cycle_desc: ''
	})
	const query = ref({
		page: 1,
		limit: 20
	})
	const total = ref(0)
	const configList = ref([])

	// 获取结算周期列表
	const getSettleCycleConfigList = () => {
		getSettleCycleConfigListApi(query.value).then(res => {
			total.value = res.other.total
			configList.value = res.data
		}).catch(err => {
			uni.showToast({
				title: err.message,
				icon: 'none'
			})
		}).finally(() => {
			setTimeout(() => {
				isLoading.value = false
			}, 500)
		})
	}
	// 规则
	const formRules = {
		cycle_value: [{
			required: true,
			message: '请输入账期',
			trigger: ['change', 'blur']
		}],
		cycle_name: [{
			required: true,
			message: '请输入周期名称',
			trigger: ['change', 'blur']
		}],
		cycle_desc: [{
			required: true,
			message: '请输入周期描述',
			trigger: ['change', 'blur']
		}],
		cycle_rate: [{
			required: true,
			message: '请输入周期比例',
			trigger: ['change', 'blur']
		}, {
			pattern: /^([1-9]\d?|100)$/,
			message: '请输入1-100之间的正整数',
			trigger: ['change', 'blur']
		}],
	}
	// 新增/编辑配置
	const submitForReview = () => {
		formRef.value?.validate((valid) => {
			if (valid) {
				submitcycleTempApi(config.value, 'edit').then(res => {
					if (res.code == 0) {
						uni.showToast({
							title: res.message,
							mask: true,
							success() {
								setTimeout(() => {
									showPopup.value = false
									getSettleCycleConfigList()
								}, 800)
							}
						})
					}
				}).catch(err => {
					uni.showToast({
						title: err.message,
						icon: "none"
					})
				})
			} else {
				uni.showToast({
					title: '请检查必填项',
					icon: 'error',
				})
			}
		})
	}
	// 切换开关
	const changeActiveSwitch = (value, type, item) => {
		let obj = {
			id: item.id,
			field: type,
			value: value
		}
		cycleUpdateApi(obj).then(res => {
			if (res.code == 0) {
				uni.showToast({
					title: res.message,
					success() {
						setTimeout(() => {
							getSettleCycleConfigList()
						}, 800)
					}
				})
			}
		}).catch(() => {
			uni.showToast({
				title: err.message,
				icon: 'none'
			})
		})
	}
	// 更新页码
	const changePage = (e) => {
		query.value.page = e.current
		getSettleCycleConfigList()
	}
	// 弹出层关闭
	const closePopup = () => {
		config.value = {
			id: 0,
			cycle_type: 1,
			cycle_name: '',
			cycle_rate: '',
			cycle_value: '',
			cycle_desc: ''
		}
		formRef.value.resetFields()
	}
	// 编辑弹窗
	const editPopup = (item) => {
		showPopup.value = true
		config.value = JSON.parse(JSON.stringify(item))
	}
	// 账期输入框改变
	const handleCycleValueInput = (value) => {
		config.value.cycle_name = `T${value}`
		config.value.cycle_desc = `账期${value}天，到账${config.value.cycle_rate}%`
	}
	// 比例输入框改变
	const handleCycleRateInput = (value) => {
		config.value.cycle_desc = `账期${config.value.cycle_value}天，到账${value}%`
	}
</script>

<style scoped lang="scss">
</style>